package util;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

/**
 * Created by Choisaaaa on 2018/6/19.
 * 随机生成测试用例数据
 */
public class SortTestHelper {
    //SortTestHelper 不允许产生任何实例
    private SortTestHelper(){}

    // 生成有n个元素的随机数组,每个元素的随机范围为[rangeL, rangeR]
    //Math.random() ： [0,1)
    //(int)2.9 = 2
    public static Integer[] generateRandomArray(int n,int rangeL,int rangeR){
        assert rangeL <= rangeR;
        Integer[] arr = new Integer[n];
        for(int i= 0 ; i<n;i++){
            arr[i] = new Integer((int)(Math.random()*(rangeR - rangeL + 1) + rangeL));
        }
        return arr;
    }

    //打印arr数组的所有数据
    public static void printArray(Object arr[]){
        for(int i= 0;i<arr.length;i++){
            System.out.println(arr[i]);
        }
    }

    //判断数组是否有序
    public static boolean isSorted(Comparable[] arr){
        for (int i = 0; i < arr.length ;i++){
            if (arr[i].compareTo(arr[i+1])>0) {
                return false;
            }
        }
        return true;
    }

    //判断正确性和时间
    public static void testSort(String sortClassName,Comparable[] arr){
        try {
            Class sortClass = Class.forName(sortClassName);
            Method sortMethod = sortClass.getMethod("sort",new Class[]{Comparable[].class});
            // 排序参数只有一个，是可比较数组arr
            Object[] params = new Object[]{arr};
            long startTime = System.currentTimeMillis();
            // 调用排序函数
            sortMethod.invoke(null,params);
            long endTime = System.currentTimeMillis();
            assert isSorted( arr );
            System.out.println( sortClass.getSimpleName()+ " : " + (endTime-startTime) + "ms" );
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
       Integer arr[] = SortTestHelper.generateRandomArray(10,6,5);
        SortTestHelper.printArray(arr);
        SortTestHelper.testSort("O2_Selection_Sort.SelectionSort",arr);
    }



}
